var md5 = require('md5.js')
import config from 'config.js'

var wordtable = ['de facto', 'pectic', 'decade', 'brokerage', 'panic', 'dichloroethylene', 'periodic', 'frequency', 'Fourier', 'mixture']

var jsonheadparam = "appId={0}" + "&" +
  "version={1}" + "&" +
  "method={2}" + "&" +
  "timestamp={3}" + "&" +
  "uuId={4}" + "&" +
  "sign={5}" + "&" +
  "lang={6}" + "&fill=";

Date.prototype.Format = function (fmt) { //author: meizz 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function sendRequest(method_name, param, successfun, failfun) {
  var timeStamp = new Date().Format("yyyyMMddhhmmss");
  // var uu_id = uuid(40, 16);
  var uu_id = guid();
  console.info('uuid:' + uu_id);
  var requestHead = getRequestHead(timeStamp, method_name, uu_id);
  for (var key in param) {
    console.log("属性：" + key + ",值：" + param[key]);
  }
  var requestData = requestHead + JSON.stringify(param);
  console.info(requestData);
  wx.showLoading({
    title: '加载中',
  });
  wx.request({
    url: config.app_server,
    data: requestData,
    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    header: {
      'content-type': 'text/html;charset=utf-8'
    },
    dataType: "json",
    success: successfun,
    fail: failfun,
    complete: function () {
      // complete
      wx.hideLoading();
    }
  })

}
function getRequestHead(timeStamp, method, uuid) {
  var number = parseInt(timeStamp);
  var index = number % 10;
  var message = config.app_id + config.app_version + method + timeStamp + uuid + wordtable[index];
  console.info("message:"+message);
  var sign = md5.md5(message);
  var requesthead = String.format(jsonheadparam, config.app_id, config.app_version, method, timeStamp, uuid, sign, 'zh-hans');
  var pading192String = requesthead;
  for (var i = 0; i < 192 - requesthead.length; i++) {
    pading192String = pading192String + '0';
  }
  return pading192String;
}

String.format = function () {
  if (arguments.length == 0)
    return null;

  var str = arguments[0];
  for (var i = 1; i < arguments.length; i++) {
    var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
    str = str.replace(re, arguments[i]);
  }
  return str;
}


function guid() {
  return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function stringToBytes(str) {
  var ch, st, re = [];
  for (var i = 0; i < str.length; i++) {
    ch = str.charCodeAt(i);  // get char   
    st = [];                 // set up "stack"  
    do {
      st.push(ch & 0xFF);  // push byte to stack  
      ch = ch >> 8;
    }
    while (ch);
    // add stack contents to result  
    // done because chars have "wrong" endianness  
    re = re.concat(st.reverse());
  }
  // return an array of bytes  
  return re;
}

module.exports = {
  getRequestHead: getRequestHead,
  sendRequest: sendRequest
}